package com.BlcokingQueue;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueTest {
    public static void main(String[] args) throws InterruptedException {
        test4();
    }

    /*
    抛出异常
    * */
    public static void test1(){
        //第一组，会抛出异常的
        //队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));
        //会抛出异常 Exception in thread "main" java.lang.IllegalStateException: Queue full
//        System.out.println(blockingQueue.add("d"));

        System.out.println(blockingQueue.element());

        for (int i = 0; i < 4; i++) {
            System.out.println(blockingQueue.remove());
        }
        //会抛出异常  Exception in thread "main" java.util.NoSuchElementException
    }
    /*
    有返回值
    * */
    public static void test2(){
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        //添加
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
//        System.out.println(blockingQueue.offer("d"));//false，不抛出异常

        //取出头元素
        System.out.println(blockingQueue.peek());

        //移除,poll不抛出异常，返回值为null
        for (int i = 0; i < 4; i++) {
            System.out.println(blockingQueue.poll());
        }

    }
    /*
    阻塞等待
    * */
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        //添加
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //移除,poll不抛出异常，返回值为null
        for (int i = 0; i < 3; i++) {
            System.out.println(blockingQueue.take());
        }
    }
    /*
    超时等待
    * */
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        //添加
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        blockingQueue.offer("d", 2,TimeUnit.SECONDS);

        for (int i = 0; i < 3; i++) {
            System.out.println(blockingQueue.poll());
        }
        System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
    }
}
